package com.example.appcontact;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

import com.example.base.BaseTabActivity;
import com.example.connect.AsyncTask_Api;
import com.example.connect.AsyncTask_ApiListener;
import com.example.connect.CallApi;
import com.example.connect.ScreenStopper;
import com.example.model.Contacts;
import com.example.model.OutLogin;
import com.example.model.OutProfile;
import com.example.model.OutResult;
import com.example.util.ConnectionException;
import com.example.util.EmptyDataException;
import com.example.util.SharedPreferencesDB;
import com.example.util.TokenUnableException;
import com.example.util.Util;

public class A005MyProfile extends BaseTabActivity implements OnClickListener,
		AsyncTask_ApiListener, OnItemSelectedListener {
	private static final int TYPE_UPDATE_MY_PROFILE = 72;
	private static final int TYPE_GET_MY_PROFILE = 71;
	private EditText 
	                 et_firstname, 
                     et_lastname,
                     et_email, 
                     et_home_phone, 
	                 et_address, 
	                 et_mobile,
	                 et_company_name,
	                 et_company_email,
	                 et_company_address,
	                 et_company_website,
	                 et_company_phone; 
			         
	private Spinner sn_gender;
	private Button  btn_birthday;
	private int mGender;
	private static final int DATE_DIALOG_ID = 0;
	private long birthday;
	private boolean isEdit = false;
	private OutProfile mOutProfile;
	private LinearLayout item_a003_lr_total;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		openDatabase();
		initView();
	}

	public void onStart() {
		super.onStart();
	}

	private void initView() {
		setContentView(R.layout.a005_my_profile);

		item_a003_lr_total = (LinearLayout) this.findViewById(R.id.item_a003_lr_total);
		et_home_phone      = (EditText) findViewById(R.id.a005_et_phone);
		et_address    = (EditText) this.findViewById(R.id.a005_et_address);
		et_email      = (EditText) findViewById(R.id.a005_et_email);
		et_firstname  = (EditText) findViewById(R.id.a005_et_firstname);
		et_mobile     = (EditText) findViewById(R.id.a005_et_mobile);
		et_lastname   = (EditText) findViewById(R.id.a005_et_lastname);
		btn_birthday  = (Button) this.findViewById(R.id.a005_btn_birthday);
		sn_gender     = (Spinner) this.findViewById(R.id.a005_sn_gender);
		
		et_company_name    = (EditText) this.findViewById(R.id.a005_et_company_name);
		et_company_website = (EditText) this.findViewById(R.id.a005_et_company_website);
		et_company_email = (EditText) this.findViewById(R.id.a005_et_company_email);
		et_company_phone   = (EditText) this.findViewById(R.id.a005_et_company_phone);
		et_company_address = (EditText) this.findViewById(R.id.a005_et_company_address);
		
		btn_birthday.setOnClickListener(this);
		sn_gender.setOnItemSelectedListener(this);
		setEnabled(false);
		initData();
	}

	private void initData() {
		SharedPreferencesDB db = new SharedPreferencesDB(this);
		getDataFromDatabase(Integer.parseInt(db.getPrefId()));
	}
	private void getDataFromDatabase(int i) {
		try {
			mOutProfile = (OutProfile) mDB.getProfile(i);
			if (mOutProfile != null) {
				Log.e("SON GET", mOutProfile.toString());
				et_email.    setText(mOutProfile.get_email());
				et_home_phone.    setText(mOutProfile.get_home_phone());
				et_address.  setText(mOutProfile.get_home_address());
				et_mobile.  setText(mOutProfile.get_mobile());
				et_firstname.setText(mOutProfile.get_first_name());
				et_lastname. setText(mOutProfile.get_last_name());
				sn_gender.setSelection(mOutProfile.get_gender());
				
				try{
					String temp  = mOutProfile.get_birthday();
					Log.e("Temp date birthday", "date birthday get form database :" + temp);
					if(temp != null && !temp.equalsIgnoreCase("") ){
						birthday = Long.parseLong(temp);
					}else{
						birthday  = new Date().getTime();
					}
					Date t  = new Date(birthday);
					String newstring = new SimpleDateFormat("dd/MM/yyyy").format(t);
					btn_birthday.setText(newstring);
					
				}catch(Exception e){
					e.printStackTrace();
				}
				et_company_name.setText(mOutProfile.get_company_name());
				et_company_website.setText(mOutProfile.get_company_website());
				et_company_email.setText(mOutProfile.get_company_email());
				et_company_phone.setText(mOutProfile.get_company_phone());
				et_company_address.setText(mOutProfile.get_company_address());
				
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.a005_btn_birthday:
			Log.d("TAG","Onclick Button Birthday");
			showDialog(DATE_DIALOG_ID);
			break;

		default:
			break;
		}
	}

	@Override
	public Object callApi(int serachType, Object apidata) {
		if (serachType == TYPE_UPDATE_MY_PROFILE) {
			String token = new SharedPreferencesDB(this).getPrefToken();
			OutResult out = new OutResult();
			try {
				out = CallApi.getUpdateProfile(this,
						createHashMapUpdateProfile(), token);
			} catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			} catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			} catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			} catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
		} else if (serachType == TYPE_GET_MY_PROFILE) {
			String token = new SharedPreferencesDB(this).getPrefToken();
			List<String> data = new ArrayList<String>();
			data.add(token);
			return CallApi.getMyProfile(this, data);
		}
		return null;
	}

	@Override
	public void finishApi(int serachType, Object apiresult) {
		try {
			if (serachType == TYPE_UPDATE_MY_PROFILE) {
				OutResult out = (OutResult) apiresult;
				if (out.getStatus()) {
					SharedPreferencesDB pre = new SharedPreferencesDB(this);
					pre.setPrefUpdateId(true);
						mDB.updateProfile(mOutProfile);
//					    getDataFromDatabase(mOutProfile.getId());

					Util.showDialog(A005MyProfile.this, R.string.update,
							out.getMessage(), R.string.ok,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									// getMyProfile();
								}
							});
				}

			} else if (serachType == TYPE_GET_MY_PROFILE) {
				OutLogin out = (OutLogin) apiresult;
				if (out != null) {
					Log.e("SON", out.toString());
					if (!mDB.checkEmail(out.getProfile().getId())) {
						mDB.createProfile(out.getProfile());
					} else {
						mDB.updateProfile(out.getProfile());
					}
					getDataFromDatabase(out.getProfile().getId());
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (serachType == TYPE_UPDATE_MY_PROFILE) {

			}
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
		this.mGender = arg2;
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	// updates the date in the TextView
	
	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
			Calendar  calendar  = Calendar.getInstance();
			calendar.set(year, monthOfYear, dayOfMonth);
			birthday  = calendar.getTimeInMillis();
			Date t  = new Date(birthday);
			String newstring = new SimpleDateFormat("dd/MM/yyyy").format(t);
			btn_birthday.setText(newstring);
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			Log.d("A005 Birthday" , "date :" + birthday);
			Date t  = new Date(birthday);
			Calendar  calendar  = Calendar.getInstance();
			calendar.setTime(t);
			return new DatePickerDialog(this, mDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
		}
		return null;
	}

	

	private HashMap<String, String> createHashMapUpdateProfile() {
		HashMap<String, String> hashMap = null;
		try {
			hashMap = new HashMap<String, String>();

			final String mFirstname       = et_firstname.getText().toString();
			final String mLastname        = et_lastname.getText().toString();
			final String mEmail           = et_email.getText().toString();
			final String mPhone           = et_home_phone.getText().toString();
			final String mBirthday        = String.valueOf(birthday);
			final String mMobile          = et_mobile.getText().toString();
			final String mAddress         = et_address.getText().toString();
			final String mCompanyPhone    = et_company_phone.getText().toString();
			final String mCompanyName     = et_company_name.getText().toString();
			final String mCompanyEmail    = et_company_email.getText().toString();
			final String mCompanyAddress  = et_company_address.getText().toString();
			final String mCompanyWebsite  = et_company_website.getText().toString();
			
			

			
				hashMap.put("properties[first_name]", mFirstname);
				hashMap.put("properties[last_name]", mLastname);
				hashMap.put("properties[home_phone]", mPhone); // number
				hashMap.put("properties[mobile]", mMobile); 
				hashMap.put("properties[home_address]", mAddress);
				hashMap.put("properties[gender]",  mGender +""); // 1: none | 0: male | 2 : female
				hashMap.put("properties[birthday]", mBirthday);
				hashMap.put("properties[company_name]", mCompanyName);
				hashMap.put("properties[company_phone]", mCompanyPhone);
				hashMap.put("properties[company_website]", mCompanyWebsite);
				hashMap.put("properties[company_email]", mCompanyEmail);
				hashMap.put("properties[company_address]", mCompanyAddress);

			mOutProfile.set_first_name(mFirstname);
			mOutProfile.set_last_name(mLastname);
			mOutProfile.set_home_phone(mPhone);
			mOutProfile.set_birthday(mBirthday);
			mOutProfile.set_mobile(mMobile);
			mOutProfile.set_home_address(mAddress);
			mOutProfile.set_gender(mGender);
			mOutProfile.set_email(mEmail);
			
			mOutProfile.set_company_address(mCompanyAddress);
			mOutProfile.set_company_phone(mCompanyPhone);
			mOutProfile.set_company_name(mCompanyName);
			mOutProfile.set_company_email(mCompanyEmail);
			mOutProfile.set_company_website(mCompanyWebsite);

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (hashMap != null)
				Log.e("SON 005", "HashMap: " + hashMap.toString());
		}
		return hashMap;
	}

	

	@Override
	public void notificationRefresh(List<Contacts> contacts) {
	}

	@Override
	public void notificationGetNotifi(List<String> email) {
	}

	private void changeLayoutEditDone() {
		if (isEdit) {
			Util.hideSoftKeyboard(this.getApplicationContext(), et_email);
			Util.showDialog(mContext, R.string.update, R.string.msg_update,
					R.string.ok, R.string.cancel,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							getUpdate();
						}
					}, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
//							if(which == 0){
//								getDataFromDatabase(mOutProfile.getId());
//							}
							
						}
					});
		}
		isEdit = !isEdit;
		((A003Contact) getParent()).setIsSettingDone(isEdit);
		setEnabled(isEdit);
	}

	private void getUpdate() {
		if (Util.getNetworkStatus(this)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_UPDATE_MY_PROFILE, 0,
					ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}

	private void setEnabled(boolean isEnabled){
		et_firstname.setEnabled(isEnabled);
        et_lastname.setEnabled(isEnabled);
        et_email.setEnabled(isEnabled);
        et_mobile.setEnabled(isEnabled);
        et_home_phone.setEnabled(isEnabled);
        et_address.setEnabled(isEnabled); 
        et_company_name.setEnabled(isEnabled);
        et_company_address.setEnabled(isEnabled);
        et_company_email.setEnabled(isEnabled);
        et_company_website.setEnabled(isEnabled);
        et_company_phone.setEnabled(isEnabled); 
        sn_gender.setEnabled(isEnabled);
        btn_birthday.setEnabled(isEnabled);
	}

	public void btDoneClicked() {
		changeLayoutEditDone();

	}

	@Override
	public void tokenExpride() {
		Util.startLogin(this.getParent());

	}
}
